/**
 *  @Author MJreams
 *  @Time 2021/12/6 12:31:00
 *
**/
package controller

import (
	"Educational/pkg/log"
	"Educational/utils/errmsg"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"golang.org/x/net/publicsuffix"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"strconv"
	"time"
)

func  (c *Controller)Login(ctx *gin.Context){
	//var user entity.User
	username := ctx.PostForm("username")
	password := ctx.PostForm("password")

	if username == "" || password ==""{
		ctx.JSON(http.StatusBadRequest,gin.H{
			"status" : "False",
		})
		return
	}
	loginUrl := c.config.Urls.LoginUrl + string(strconv.FormatInt((time.Now().UnixNano() / 1e6), 10)) + "&username=" + username + "&password=" + password
	v := url.Values{
		"username":[]string{username},
		"password":[]string{password},
	}
	//fmt.Println(c.userInfo)
	options := cookiejar.Options{
		PublicSuffixList: publicsuffix.List,
	}
	jar, _ := cookiejar.New(&options)
	client := &http.Client{
		Jar: jar,
	}
	// {"name":"0","msg":"密码错误！如您忘记密码，请联系学院秘书进行密码重置。"})  142
	//{"name":"2","msg":"请输入正确的用户名！"})	94
	//({"name":"1"})	55
	//

	// 如果成功登陆，则保存当前的用户Cookie,后续只需要直接根据用户名找对Cookie，进行后续操作
	resp, err := client.PostForm(loginUrl,v)
	if err != nil {
		log.Logger.Debug("LoginPost请求错误", zap.Error(err),zap.String("code", err.Error()))
	}

	loginCode  := resp.ContentLength
	if loginCode == 55 {
		c.userClient[username] = client
		// 后端设置一个自己的cookie，这样就可以根据 cookie -> username -> 教务端的cookie,设置cookie时长为半个小时，半小时后需要重新进行登陆
		// https://www.cnblogs.com/qzhc/p/13454576.html
		ctx.SetCookie("username", username, 1800, "/", "localhost", false, true)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"status" : loginCode,
		"msg" : errmsg.GetErrorMsg(loginCode),
	})


}
